package com.edu.internship.config.interceprot;

import com.edu.internship.busi.entity.UserToken;
import com.edu.internship.config.context.UserContextHolder;
import com.edu.internship.config.redis.RedisUtil;
import com.edu.internship.glabal.constants.ResultCodeEnum;
import com.edu.internship.glabal.exception.BusinessException;
import com.edu.internship.util.JwtUtils;
import com.edu.internship.util.Tools;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //从请求头中获取token
        String token = request.getHeader("token");
        if (Tools.isBlank(token)) {
            token = request.getParameter("token");
        }
       // 判读token是否为空
          if(token.length() == 4 || token.isEmpty()) {
            throw new BusinessException(ResultCodeEnum.ACCESS_DENIED_ERROR,"token为空");
          }
        if(Tools.isBlank(redisUtil.get(token))){
            throw new BusinessException(ResultCodeEnum.VALIDATE_NOT_ACCESS,"token超时过期，请重新登录");
        }
        return true;

    }
}
